import { getTokenSync } from "@/utils/auth";
import config from "./config";
import { last, get } from "lodash";
const duration = 1500;
const API_URL = config.baseURL;

type MethodType = | "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined;
type ResPonseType<T> = { code:number, data:T, msg:string }
let header: any = {
  "content-type": "application/x-www-form-urlencoded",
};

const whiteList = ["pages/login/index"]

export const request = <T>(
  url: String,
  method: MethodType,
  params: {[key:string]:any} = {},
  needLoading: boolean = false
): Promise<T> => {
  needLoading && uni.showLoading({ title: "加载中",  mask: true });

  return new Promise((resolve, reject)=>{
    getTokenSync() && (header["Authorization"] = "Bearer " + getTokenSync());
    uni.request({
      url: API_URL + url,
      method: method,
      data: {...params},
      header,
      success: (res) => {
        if(!res.data) return reject(res);
          const { code, data, msg } = res.data as ResPonseType<T>;

          if(code === 200) return resolve(data);

           if (code == 401) {
            uni.showToast({
              title:!getTokenSync() ? "暂未登录，请登录" : "登录超时，请重新登录",
              icon: "none",
              duration: duration,
            });

            if(whiteList.includes(get(last(getCurrentPages()), "route", ''))) return

            setTimeout(() => {
              uni.navigateTo({ url: "/pages/login/index"});
            }, duration);
            return reject(res);
          }

          uni.showToast({
            title: msg,
            icon: "none",
            duration: duration,
          });
      },
      fail: (res: any) => {
        console.log(res,'faisl');
        reject(res);
      },
      // 完成之后关闭加载效果
      complete: (res: any) => {
        uni.hideLoading();
      },
    });
  });
};
